package messageMeTransfer.utilities;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import messageMeTransfer.interfaces.IListener;
import messageMeTransfer.interfaces.IPackage;

public class PackageReciever extends Thread {
	
	private ObjectInputStream inputStream = null;
	private List<IListener> listeners = new ArrayList<IListener>();

	public PackageReciever(ObjectInputStream objectInputStream) {
		this.inputStream = objectInputStream;
	}

	public synchronized void addListener(IListener listener) {
		this.listeners.add(listener);
	}

	public void run() {

		try {
			IPackage iPackage;
			while ((iPackage = (IPackage) inputStream.readObject()) != null) {
				this.addPackage(iPackage);
			}
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
	}

	public synchronized void addPackage(IPackage iPackage) {
		for (IListener listener : this.listeners) {
			listener.packageRecieved(iPackage);
		}
	}
}
